package pers.lls.im.core.bootstrap.handler;

import com.alibaba.fastjson.JSON;
import pers.lls.im.core.bootstrap.handler.base.AbstractHandler;
import pers.lls.im.core.bootstrap.handler.base.Handler;
import pers.lls.im.core.bootstrap.handler.base.HandlerService;
import pers.lls.im.core.common.bean.ChatMessage;
import pers.lls.im.core.common.bean.TransType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;


/**
 * @author lihuan
 * @version V1.0 创建时间：2019/8/02
 * Copyright 2019 by landray & STIC
 */
@Slf4j
@ChannelHandler.Sharable
public class DefaultHandler extends AbstractHandler {


    private Handler handler;

    public DefaultHandler(Handler handler) {
        super(handler);
        this.handler = handler;
    }

    @Override
    protected void dealWsfMessage(ChannelHandlerContext ctx, WebSocketFrame msg) {
        //empty
    }

    @Override
    protected void dealFhrMessage(ChannelHandlerContext ctx, FullHttpRequest msg) {
        //nothing
    }

    @Override
    protected void dealTwsfMessage(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        Channel channel = ctx.channel();
        HandlerService handlerService;
        if (handler instanceof HandlerService) {
            handlerService = (HandlerService) handler;
        } else {
            log.error("no handler");
            return;
        }
        ChatMessage chatMessage = JSON.parseObject(msg.text(), ChatMessage.class);
        chatMessage.setTime(new Date());
        if (chatMessage.getType().equals(TransType.REGISTRY.getCode())) {
            handlerService.registry(channel, chatMessage);
        } else if (chatMessage.getType().equals(TransType.SEND_TO_ONE.getCode())) {
            handlerService.verify(channel, chatMessage);
            handlerService.sendToOne(channel, chatMessage);
        } else if (chatMessage.getType().equals(TransType.SEND_TO_GROUP.getCode())) {
            handlerService.verify(channel, chatMessage);
            handlerService.sendToGroup(channel, chatMessage);
        }else if (chatMessage.getType().equals(TransType.UNREAD_MESSAGE.getCode())){
            handlerService.getUnreadMessage(channel,chatMessage);
        }else if (chatMessage.getType().equals(TransType.DELETE_UNREAD.getCode())){
            handlerService.removeUnread(channel, chatMessage);
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("invoke DefaultHandler.channelActive");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
